<template>
    <div class="address-management">
        <!-- 页面标题和操作栏 -->
        <div class="page-header">
            <div class="title-section">
                <h1 class="page-title">地址管理</h1>
                <p class="page-subtitle">管理您的收货地址信息</p>
            </div>
            <el-button type="primary" icon="el-icon-plus" class="add-btn" @click="openDialog('add')">
                新增地址
            </el-button>
        </div>

        <!-- 地址列表 -->
        <div class="address-list" v-if="addressList.length > 0">
            <div class="list-header">
                <span class="total-count">共 {{ addressList.length }} 个地址</span>
            </div>

            <el-card v-for="(item, index) in addressList" :key="item.id" class="address-item"
                :class="{ 'default-address': item.isDefault == 1 }" shadow="hover">
                <div class="address-content">
                    <!-- 地址图标和状态 -->
                    <div class="address-icon">
                        <i class="el-icon-location-information"
                            :style="{ color: item.isDefault == 1 ? '#F56C6C' : '#409EFF' }"></i>
                    </div>

                    <!-- 地址信息 -->
                    <div class="info">
                        <div class="name-phone">
                            <span class="name">{{ item.receiveName }}</span>
                            <span class="phone">{{ item.phone }}</span>
                            <el-tag v-if="item.isDefault == 1" type="danger" size="small" class="default-tag">
                                <i class="el-icon-star"></i>默认地址
                            </el-tag>
                        </div>
                        <div class="address-text">
                            <span class="region">{{ formatRegion(item.region) }}</span>
                            <span class="detail">{{ item.street }}</span>
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="actions">
                        <el-button type="text" icon="el-icon-edit" class="action-btn"
                            @click="openDialog('edit', index)">
                            编辑
                        </el-button>
                        <el-button type="text" icon="el-icon-delete" class="action-btn delete-btn"
                            @click="handleDelete(item.id)">
                            删除
                        </el-button>
                        <el-button type="text" :disabled="item.isDefault == 1" class="action-btn"
                            @click="setDefault(item.id)">
                            <i class="el-icon-check"></i>设为默认
                        </el-button>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 空状态 -->
        <div class="empty-state" v-else>
            <div class="empty-content">
                <i class="el-icon-location-information empty-icon"></i>
                <h3>暂无收货地址</h3>
                <p>您还没有添加任何收货地址，现在添加一个吧</p>
                <el-button type="primary" icon="el-icon-plus" @click="openDialog('add')">
                    添加地址
                </el-button>
            </div>
        </div>

        <!-- 地址表单弹窗 -->
        <el-dialog :title="dialogType === 'add' ? '新增地址' : '编辑地址'" :visible.sync="dialogVisible" width="600px"
            :close-on-click-modal="false" custom-class="address-dialog">
            <address-form v-if="dialogVisible" :form-data="currentAddress" :current-index="currentIndex"
                @submit="(formData) => handleSubmit(formData, dialogType)" @cancel="dialogVisible = false" />
        </el-dialog>
    </div>
</template>

<script>
import AddressForm from './AddressForm.vue'
import { batchDeleteAddress, AddAddress, updateAddress, DeleteAddress, SetDefault, getList } from '@/api/user/address'

export default {
    name: 'AddressManagement',
    components: { AddressForm },
    data() {
        return {
            dialogVisible: false,
            dialogType: 'add',
            currentIndex: -1,
            addressList: [],
            loading: false
        }
    },
    computed: {
        currentAddress() {
            return this.dialogType === 'add'
                ? { name: '', phone: '', region: [], detail: '', isDefault: false }
                : { ...this.addressList[this.currentIndex] }
        }
    },
    methods: {
        async loadDate() {
            this.loading = true
            try {
                const res = await getList();
                console.log('res', res.data.data.records);
                this.addressList = res.data.data.records.map(({ privince, city, street, price, ...rest }) => ({
                    ...rest,
                    region: [privince, city, street],
                }));

                res.data.data.records.forEach((item) => {
                    if (item.isDefault === 1) {
                        this.currentIndex = item.id;
                    }
                });
            } catch (error) {
                console.error('请求出错:', error);
                this.$message.error('加载地址列表失败');
            } finally {
                this.loading = false
            }
        },

        openDialog(type, index = -1) {
            this.dialogType = type
            this.currentIndex = index
            this.dialogVisible = true
        },

        async handleSubmit(formData, type) {
            const isAdd = type === 'add'
            try {
                let res
                if (isAdd) {
                    res = await AddAddress(formData);
                } else {
                    res = await updateAddress(formData);
                }

                if (res.data.code === 1) {
                    this.$message.success(isAdd ? '添加成功' : '修改成功');
                    this.dialogVisible = false;
                    await this.loadDate(); // 重新加载数据确保数据一致性
                } else {
                    this.$message.error(res.data.msg || '操作失败');
                }
            } catch (error) {
                this.$message.error('操作失败: ' + (error.message || '未知错误'));
            }
        },

        async handleDelete(id) {
            try {
                await this.$confirm('确定要删除该地址吗？', '提示', {
                    type: 'warning',
                    confirmButtonText: '确定删除',
                    cancelButtonText: '再想想',
                    confirmButtonClass: 'delete-confirm-btn'
                });

                const res = await DeleteAddress(id);
                if (res.data.code === 1) {
                    this.$message.success('删除成功');
                    this.addressList = this.addressList.filter(item => item.id !== id);
                } else {
                    this.$message.error(res.data.msg || '删除失败');
                }
            } catch (error) {
                if (error !== 'cancel') {
                    this.$message.error('删除失败: ' + (error.message || '未知错误'));
                }
            }
        },

        async setDefault(id) {
            try {
                const res = await SetDefault(id, this.currentIndex);
                if (res.data.code == 1) {
                    this.$message.success('设置默认地址成功');
                    this.addressList.forEach(item => {
                        item.isDefault = item.id === id ? 1 : 0;
                    });
                } else {
                    this.$message.error(res.data.msg || '设置失败');
                }
            } catch (error) {
                this.$message.error('设置失败: ' + (error.message || '未知错误'));
            }
        },

        formatRegion(region) {
            return region ? region.join(' / ') : ''
        }
    },

    mounted() {
        this.loadDate();
    }
}
</script>

<style lang="less" scoped>
@primary-color: #409EFF;
@default-color: #F56C6C;
@success-color: #67C23A;
@warning-color: #E6A23C;
@error-color: #F56C6C;
@info-color: #909399;

.address-management {
    padding: 24px;
    max-width: 900px;
    margin: 0 auto;
    background: #f8f9fa;
    min-height: 100vh;

    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        margin-bottom: 24px;
        padding-bottom: 16px;
        border-bottom: 1px solid #e8e8e8;

        .title-section {
            .page-title {
                margin: 0;
                font-size: 24px;
                font-weight: 600;
                color: #303133;
                line-height: 1.2;
            }

            .page-subtitle {
                margin: 8px 0 0;
                color: @info-color;
                font-size: 14px;
            }
        }

        .add-btn {
            height: 40px;
            padding: 0 20px;
            font-weight: 500;
            box-shadow: 0 2px 6px rgba(@primary-color, 0.2);

            &:hover {
                transform: translateY(-1px);
                box-shadow: 0 4px 12px rgba(@primary-color, 0.3);
            }
        }
    }

    .address-list {
        .list-header {
            margin-bottom: 16px;

            .total-count {
                color: @info-color;
                font-size: 14px;
            }
        }

        .address-item {
            margin-bottom: 16px;
            border-radius: 12px;
            transition: all 0.3s ease;
            border: 1px solid #e8e8e8;

            &.default-address {
                border-left: 4px solid @default-color;
                background: linear-gradient(135deg, #fff 0%, #fff5f5 100%);
            }

            &:hover {
                transform: translateY(-2px);
                box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
            }

            .address-content {
                display: flex;
                align-items: flex-start;
                padding: 8px 0;

                .address-icon {
                    margin-right: 16px;
                    padding-top: 4px;

                    i {
                        font-size: 24px;
                        transition: all 0.3s;
                    }
                }

                .info {
                    flex: 1;
                    min-width: 0;

                    .name-phone {
                        display: flex;
                        align-items: center;
                        margin-bottom: 8px;
                        flex-wrap: wrap;
                        gap: 8px;

                        .name {
                            font-size: 16px;
                            font-weight: 600;
                            color: #303133;
                        }

                        .phone {
                            color: @info-color;
                            font-size: 14px;
                        }

                        .default-tag {
                            border: none;
                            background: linear-gradient(135deg, @default-color, #f78989);
                            color: white;

                            i {
                                margin-right: 4px;
                            }
                        }
                    }

                    .address-text {
                        color: #606266;
                        line-height: 1.6;

                        .region {
                            font-weight: 500;
                        }

                        .detail {
                            margin-left: 8px;
                            color: @info-color;
                        }
                    }
                }

                .actions {
                    display: flex;
                    flex-direction: column;
                    gap: 8px;
                    margin-left: 20px;
                    flex-shrink: 0;

                    .action-btn {
                        padding: 6px 12px;
                        border-radius: 6px;
                        transition: all 0.3s;

                        &:hover {
                            background: #f5f7fa;
                            transform: translateX(2px);
                        }

                        &.delete-btn:hover {
                            color: @error-color;
                            background: #fef0f0;
                        }

                        &:disabled {
                            color: #c0c4cc;
                            cursor: not-allowed;

                            &:hover {
                                background: transparent;
                                transform: none;
                            }
                        }
                    }
                }
            }
        }
    }

    .empty-state {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 400px;
        text-align: center;

        .empty-content {
            .empty-icon {
                font-size: 64px;
                color: #dcdfe6;
                margin-bottom: 16px;
            }

            h3 {
                margin: 0 0 8px;
                color: #303133;
                font-size: 18px;
                font-weight: 500;
            }

            p {
                margin: 0 0 20px;
                color: @info-color;
                font-size: 14px;
            }
        }
    }
}

// 响应式设计
@media (max-width: 768px) {
    .address-management {
        padding: 16px;

        .page-header {
            flex-direction: column;
            align-items: stretch;
            gap: 16px;

            .title-section {
                text-align: center;
            }

            .add-btn {
                width: 100%;
            }
        }

        .address-content {
            flex-direction: column !important;
            align-items: stretch !important;

            .address-icon {
                margin-right: 0 !important;
                margin-bottom: 12px;
                text-align: center;
            }

            .actions {
                margin-left: 0 !important;
                margin-top: 16px;
                flex-direction: row !important;
                justify-content: space-around;
                border-top: 1px solid #f0f0f0;
                padding-top: 16px;
            }
        }
    }
}

// 动画效果
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s, transform 0.3s;
}

.fade-enter,
.fade-leave-to {
    opacity: 0;
    transform: translateY(10px);
}

// 对话框样式优化
:deep(.address-dialog) {
    .el-dialog__header {
        border-bottom: 1px solid #e8e8e8;
        padding: 20px 20px 16px;

        .el-dialog__title {
            font-weight: 600;
            color: #303133;
        }
    }

    .el-dialog__body {
        padding: 20px;
    }
}

:deep(.delete-confirm-btn) {
    background-color: @error-color !important;
    border-color: @error-color !important;

    &:hover {
        background-color: lighten(@error-color, 5%) !important;
        border-color: lighten(@error-color, 5%) !important;
    }
}
</style>